package com.youwu.demo03.FileUpload;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;

public class TCPServer {

    public static void main(String[] args) throws Exception {
        ServerSocket server = new ServerSocket(8888);
        // 无限循环上传文件
        while (true) {
            Socket socket = server.accept();
            // 多个客户端上传文件，就开启多个线程去执行上传功能
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {

                        InputStream is = socket.getInputStream();
                        File file = new File("d:\\upload");
                        if (!file.exists()) {
                            file.mkdirs();
                        }
                        /**
                         * 自定义文件名，防止同名文件被覆盖
                         * 规则：域名+毫秒数+随机数
                         */

                        String fileName = "mnmayday" + System.currentTimeMillis()
                                + new Random().nextInt(999999999) + ".jpg";

                        //FileOutputStream fos = new FileOutputStream(file + "\\1.jpg");
                        FileOutputStream fos = new FileOutputStream(file + "\\" + fileName);
                        byte[] bytes = new byte[1024];
                        int len = 0;
                        // is.read(bytes)读取客户端上传文件，永远也读取不到结束标记
                        // 因此，当文件上传成功后，read方法会进入到阻塞状态，导致服务器无法关闭
                        while (-1 != (len = is.read(bytes))) {
                            fos.write(bytes, 0, len);
                        }
                        OutputStream os = socket.getOutputStream();
                        os.write("上传成功！".getBytes());

                        fos.close();
                        socket.close();
                    } catch (IOException e) {
                        System.out.println(e.getMessage());
                    }

                }
            }).start();

        }

        // 服务器就不用关闭
        //server.close();
    }
}
